import ctypes
from ctypes import c_char_p
import os
import cv2
import sys
sys.path.append(os.path.join(os.path.abspath(os.curdir),"OCR_api.dll"))

class rect2i(ctypes.Structure):
    _fields_ = [("x", ctypes.c_int),
              ("y", ctypes.c_int),
              ("width", ctypes.c_int),
              ("height", ctypes.c_int)]

class OCR(object):
    def __init__(self,path,box):
        self.path = path
        self.box = box
        self.ocr()
    def ocr(self):
        currentdir = os.path.abspath(os.curdir)
        Objdll = ctypes.windll.LoadLibrary(os.path.join(currentdir,"OCR_api.dll"))
        Objdll.detect_ocr_file.restype = c_char_p
        engs = bytes("eng",'utf-8')
        chinese = bytes("chi_sim",'utf-8')
        rect = rect2i()
        rect.x = self.box[0]
        rect.y = self.box[1]
        rect.width = self.box[2]
        rect.height = self.box[3]
        aa = Objdll.detect_ocr_file(bytes(self.path, 'utf-8'),rect,chinese)
        b = ctypes.string_at(aa,len(aa))
        img=cv2.imread(self.path)
        cv2.namedWindow('OCR',cv2.WINDOW_NORMAL)
        cv2.putText(img,"OCR result:"+b.decode(),(int(self.box[0]), max(20, int(self.box[1])-10)), cv2.FONT_HERSHEY_SIMPLEX, 2,
                        (255, 0, 0), 2)
        cv2.imshow('OCR',img)
        cv2.waitKey()
